<?php
header('Content-Type: application/json; charset=utf-8');

/* 1. 数据库连接 */
$dbConfig = include('db_config.php');
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库连接失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 2. 定义 mi_bbs 全部字段（按文本接收）*/
$fields = [
    'user_id',          // 发帖用户 id
    'title',            // 帖子标题
    'content',          // 帖子正文
    'category',         // 分类
    'tags',             // 标签（可存 JSON 或逗号分隔）
    'attachment',       // 附件链接
    'cover',            // 封面图
    'ip',               // 发帖 IP
    'device',           // 发帖设备
    'extra'             // 扩展字段（备用）
];

/* 3. 收集参数（统一按文本处理）*/
$bind = [];
$columns = [];
$values  = [];
foreach ($fields as $f) {
    $val = trim($_POST[$f] ?? '');
    $columns[]            = "`$f`";
    $values[]             = ":$f";
    $bind[":$f"] = $val;
}

/* 可选：记录创建时间 */
$columns[] = "`created_at`";
$values[]  = "NOW()";

/* 4. 拼接并执行 SQL */
$sql = "INSERT INTO `mi_bbs` (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ")";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($bind);

    echo json_encode([
        'status'  => 'success',
        'message' => '添加成功',
        'id'      => $pdo->lastInsertId()
    ], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '添加失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
?>
